package poswar.contribute.mbean;

import javax.annotation.PostConstruct;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;

import org.apache.log4j.Logger;

import poswar.contribute.dao.QuestionDao;
import poswar.contribute.exception.QuestionWhereAnsweredException;
import poswar.contribute.model.Answer;
import poswar.contribute.model.Question;


@ManagedBean
@ApplicationScoped
public class QuestionBean {
	private static final Logger logger = Logger.getLogger(QuestionBean.class);

	private enum QUESTION_STATES  { 
		DEFINING_QUESTION,
		ANSWERING_QUESTION,
		EVALUATING_ANSWERS
	}
	
	private QUESTION_STATES state = QUESTION_STATES.DEFINING_QUESTION;
	
	private String questionField;
	
	private Question question;
	
	private QuestionDao questionDao;
	
	private Object mutex = new Object();
	
	@PostConstruct
	private void init() {
		questionDao = new QuestionDao();
		question = questionDao.load();
		
		// Deciding the state
		if (question.getText() == null) {
			state = QUESTION_STATES.DEFINING_QUESTION;
		} else {
			state = QUESTION_STATES.ANSWERING_QUESTION;
		}
	}
	
	public String defineQuestion() {
		question = Question.build(questionField);
		state = QUESTION_STATES.ANSWERING_QUESTION;
		saveState();
		
		return null;
	}

	public String finishAnswers() {
		state = QUESTION_STATES.EVALUATING_ANSWERS;		
		
		return null;
	}
	
	public String finishEvaluation() {
		for (Answer a: question.getAnswerList()) {
			logger.debug(a.getEmail() + "\t" + a.getEvaluation());
		}
		
		saveState();
		questionDao.backup(question);
		
		questionField = "";
		state = QUESTION_STATES.DEFINING_QUESTION;			
				
		return null;
	}	
	
	public String getQuestionField() {
		return questionField;
	}

	public void setQuestionField(String questionField) {
		this.questionField = questionField;
	}

	public QUESTION_STATES getState() {
		return state;
	}

	public Question getQuestion() {
		return question;
	}

	public void saveState() {
		logger.debug("Saving question state");
		questionDao.save(question);		
	}

	public void publishAnswer(Answer answer) throws QuestionWhereAnsweredException {
		if (state == QUESTION_STATES.ANSWERING_QUESTION) {
			synchronized (mutex) {
				question.publishAnswer(answer);
				questionDao.save(question);
			}
		}
	}
}

